package net.easyjava.framework;


import com.alibaba.fastjson.JSONObject;
import net.easyjava.framework.log.LogConstants;
import net.easyjava.framework.log.LogUtils;
import net.easyjava.framework.web.security.*;
import net.easyjava.tools.http.request.RequestTools;
import net.easyjava.tools.lang.StringTools;
import net.easyjava.tools.model.ModelBean;
import net.easyjava.tools.model.ModelConstants;
import net.easyjava.tools.security.SignTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * Created by wenxiaoning on 15/12/18.
 */
public class BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    /**
     * CONTENT_TYPE_JSONP = "application/javascript";
     */
    public static final String CONTENT_TYPE_JSONP = "application/javascript;charset=UTF-8";
    public static final String CONTENT_TYPE_TEXT = "text/html;charset=UTF-8";
    public static final String CONTENT_TYPE_JSON = "application/json; charset=UTF-8";

    protected static final String API_SIGN_KEY = "a2dc8a390e92ab87678a5bf922fbd5dd";


    /**
     * 检查接口是否符合安全监测
     * 现在在拦截器中完成
     * @param request
     * @param response
     */
    @Deprecated
    public ModelBean checkApi(HttpServletRequest request, HttpServletResponse response){
        String createSign = null;
        try {
            createSign = SignTools.createSign(request,API_SIGN_KEY);
        } catch (NoSuchAlgorithmException e) {
            logger.error("获取sign值失败",e.fillInStackTrace());
        }
        //获取sign
        String sign = RequestTools.getParam(request,"sign","default");
        ModelBean modelBean = new ModelBean();
        if(!sign.equalsIgnoreCase(createSign)){
            modelBean = new ModelBean("您没有访问权限");
        }
        return modelBean;

    }

    /**
     * 参数错误时返回固定语句
     * @param key
     * @return
     */
    public String paramError(String key){
        String message = String.format(ModelConstants.MESSAGE_PARAM_ERROR, key);
        return message;
    }

    /**
     * 跳转地址公用方法
     * @param url
     * @param params
     * @param request
     * @return
     */
    public ModelAndView modelAndView(String url,Map<String,Object> params,HttpServletRequest request){
        Map<String,String> params1 = RequestTools.getParams(request);
        params.putAll(params1);
        return new ModelAndView(url,params);
    }


    public ModelBean model(ModelBean model,HttpServletRequest request,HttpServletResponse response){
        return this.model(model,0l,request,response);
    }
    /**
     * 兼容jsonp的返回格式和过滤字段
     * @param model ModelBean
     * @param request
     * @param response
     * @return
     */
    public ModelBean model(ModelBean model,long begin,HttpServletRequest request,HttpServletResponse response){
        String url = RequestTools.getRealUrl(request);

        Map<String,String[]> params = request.getParameterMap();
        //返回接口记录日志
        UserSecurityBean userSecurityBean = getUserSecurityBean();
        LogUtils.logApiDetail(model, userSecurityBean, request, response);

        //过滤
        if(params.containsKey("filter")){
            String filter = RequestTools.getParam(request,"filter");
            model = new ModelBean(model.getData(),filter);
        }
        if(begin !=0){
            logger.info(LogConstants.API_TIME_SUM,new Object[]{url,(System.currentTimeMillis()-begin)});
        }
        logger.info("{}\t返回结果概要 status:{},message:{},timestamp:{}",new Object[]{url,model.getStatus(),model.getMessage(),model.getTimestamp()});
        if(params.containsKey("callback")){
            try {
                response.setContentType(CONTENT_TYPE_TEXT);
                PrintWriter out = response.getWriter();
                out.write(new String(params.get("callback")[0] + "("));
                out.write(JSONObject.toJSONString(model));
                out.write(new String(");"));
                out.flush();
                out.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e.fillInStackTrace());
            }
            return null;
        }else{
            return model;
        }
    }

    /**
     * 在页面中alert输出信息
     * @param message
     * @param response
     */
    public void printWriterAlert(String message,HttpServletResponse response){
        try {
            response.setContentType(CONTENT_TYPE_TEXT);
            PrintWriter out = response.getWriter();
            out.print("<script type=\"text/javascript\">");
            out.print("window.onload=function(){alert('"+message+"');}");
            out.print("</script>");
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e.fillInStackTrace());
        }
    }
    @Resource
    private UserSecurityOnHead userSecurityOnHead;

    @Resource
    private UserSecurityOnCookie userSecurityOnCookie;
    @Resource
    private UserSecurityAdminOnCookie userSecurityAdminOnCookie;
//
    /**
     * 获取登陆用户id
     * @return
     */
    protected UserSecurityBean getUserSecurityBean(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        UserSecurityBean userSecurityBean  = this.userSecurityOnHead.getUserSecurityBean(request);
        if(userSecurityBean == null){
            userSecurityBean  = this.userSecurityOnCookie.getUserSecurityBean(request);
        }
        return userSecurityBean;
    }

    /**
     * 获取登录用户id
     * @return
     */
    protected UserSecurityBean getUserSecurityBeanOnCookie(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        UserSecurityBean userSecurityBean  = this.userSecurityOnCookie.getUserSecurityBean(request);
        if(userSecurityBean == null){
            return null;
        }
        return userSecurityBean;
    }

    /**
     * 获取admin用户
     * @return
     */
    protected UserSecurityBean getAdminUserSecurityBeanOnCookie(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        UserSecurityBean userSecurityBean  = this.userSecurityAdminOnCookie.getUserSecurityBean(request);
        if(userSecurityBean == null){
            return null;
        }
        return userSecurityBean;
    }
}
